package net.ycxinxing.mcpebox.ui;
import android.app.Dialog;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.design.widget.TextInputEditText;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.Spinner;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.ycxinxing.mcpebox.CallbackBundle;
import net.ycxinxing.mcpebox.Pro.R;
import net.ycxinxing.mcpebox.baseActivity;
import net.ycxinxing.mcpebox.mDialog;
import net.ycxinxing.mcpebox.ui.prepareLaunch;
import net.ycxinxing.mcpebox.utils.OpenFileDlg;
import net.ycxinxing.mcpebox.utils.Utils;
import org.json.JSONArray;
import org.json.JSONException;

public class prepareLaunch extends baseActivity
{
	String packPath=null;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        // TODO: Implement this method
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_launchgame);
        initViews();
    }

    private void initViews()
    {
        final Spinner s=(Spinner)findViewById(R.id.MinecraftVarSpinner1);
        final Spinner jni=(Spinner)findViewById(R.id.MinecraftVarSpinner2);
        final File[] files=new File("/sdcard/ycxinxing/mcpebox/var/").listFiles();
        int count=files.length;
        final List<String> arr=new ArrayList<String>();
        int i=0;
        while (i < count)
        {
            if (files[i].getName().endsWith(".apk"))
            {
                arr.add(files[i].getName());
            }
            i++;
        }
        boolean novar=false;
        if (arr.size() == 0)
        {
            arr.add("无任何版本!");
            novar = true;

        }
        final List<String> arr2=new ArrayList<String>();
        final File[] jnis=new File("/data/data/" + getPackageName() + "/jnitmp/").listFiles();
        count = jnis.length;
        i = 0;
        while (i < count)
        {
            if (jnis[i].isDirectory())
            {
                arr2.add(jnis[i].getName());
            }
            i++;
        }
        if (arr2.size() == 0)
        {
            arr2.add("无任何缓存!");
        }
        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, arr);
        ArrayAdapter<String> arrayAdapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, arr2);
        jni.setAdapter(arrayAdapter2);
        s.setAdapter(arrayAdapter);
        final TextInputEditText et=(TextInputEditText)findViewById(R.id.NativePath);
        et.setFocusable(false);
        et.setLongClickable(false);
		final Button packet=(Button) findViewById(R.id.PacketPathSButton);
		packet.setOnClickListener(new OnClickListener(){
				@Override
				public void onClick(View p1)
				{
					showDialog(1234);
					// TODO: Implement this method
				}
			});
        final Button launch=(Button)findViewById(R.id.LaunchGameButton);
		final CheckBox safemodel=(CheckBox)findViewById(R.id.SafeModelCheckBox);
        launch.setOnClickListener(new OnClickListener(){
                @Override
                public void onClick(View v)
                {
					ArrayList<String> texturelist = new ArrayList<String>();
					try
					{
						JSONArray arr=new JSONArray(getSharedPreferences("data", MODE_PRIVATE).getString("texturepack", new JSONArray().toString()));
						int i=0;
						while(i<arr.length())
						{
							texturelist.add(arr.get(i).toString());
							i++;
						}
					}
					catch (JSONException e)
					{
						throw new RuntimeException(e);
					}
					if (safemodel.isChecked())
					{
                   		Utils.LaunchGamePro("/sdcard/ycxinxing/mcpebox/var/" + arr.get(s.getSelectedItemPosition()), "/data/data/" + getPackageName() + "/jnitmp/" + arr2.get(jni.getSelectedItemPosition()), null, prepareLaunch.this, null,texturelist);
					}
					else
					{
						Utils.LaunchGamePro("/sdcard/ycxinxing/mcpebox/var/" + arr.get(s.getSelectedItemPosition()), "/data/data/" + getPackageName() + "/jnitmp/" + arr2.get(jni.getSelectedItemPosition()), (ApplicationInfo)et.getTag(), prepareLaunch.this,packPath,texturelist);
					}
                    finish();
                    //Utils.LaunchGame("/sdcard/ycxinxing/mcpebox/var/"+arr.get(s.getSelectedItemPosition()),et.getText().toString(),MainActivity.this);
                    // TODO: Implement this metho
                }
            });
        launch.setEnabled(false);

        final LinearLayout nativepath=(LinearLayout)findViewById(R.id.NativePathLinearLayout1);
        safemodel.setOnCheckedChangeListener(new OnCheckedChangeListener(){
                @Override
                public void onCheckedChanged(CompoundButton p1, boolean p2)
                {
                    if (safemodel.isChecked())
                    {
                        nativepath.setVisibility(View.INVISIBLE);
                        if (!((arr.size() == 1 && arr.get(0).equals("无任何版本!")) || (arr2.size() == 1 && arr2.get(0).equals("无任何缓存!"))))
                        //if(!(arr.size()==1&&arr.get(0).equals("无任何版本!")))
                        {
                            launch.setEnabled(true);
                        }
						else
						{
							launch.setEnabled(false);
						}
                    }
                    else
                    {
                        nativepath.setVisibility(View.VISIBLE);
                        if (!((arr.size() == 1 && arr.get(0).equals("无任何版本!")) || (arr2.size() == 1 && arr2.get(0).equals("无任何缓存!") || !new File(et.getText().toString()).exists())))
                        //if(!(arr.size()==1&&arr.get(0).equals("无任何版本!")))
                        {
                            launch.setEnabled(true);
                        }
						else
						{
							launch.setEnabled(false);
						}
                    }
                    // TODO: Implement this method
                }
            });
        et.addTextChangedListener(new TextWatcher(){
				@Override
				public void beforeTextChanged(CharSequence p1, int p2, int p3, int p4)
				{
					// TODO: Implement this method
				}

				@Override
				public void onTextChanged(CharSequence p1, int p2, int p3, int p4)
				{
					// TODO: Implement this method
					if (safemodel.isClickable())
                    {
                        if (!((arr.size() == 1 && arr.get(0).equals("无任何版本!")) || (arr2.size() == 1 && arr2.get(0).equals("无任何缓存!"))))
                        //if(!(arr.size()==1&&arr.get(0).equals("无任何版本!")))
                        {
                            launch.setEnabled(true);
                        }
						else
						{
							launch.setEnabled(false);
						}
                    }
					else
					{
                        if (!((arr.size() == 1 && arr.get(0).equals("无任何版本!")) || (arr2.size() == 1 && arr2.get(0).equals("无任何缓存!") || !new File(et.getText().toString()).exists())))
                        //if(!(arr.size()==1&&arr.get(0).equals("无任何版本!")))
                        {
                            launch.setEnabled(true);
                        }
						else
						{
							launch.setEnabled(false);
						}
                    }
				}

				@Override
				public void afterTextChanged(Editable p1)
				{
					// TODO: Implement this method
				}
			});
        Button btn=(Button)findViewById(R.id.NativePathSButton1);

        btn.setOnClickListener(new OnClickListener(){
                @Override
                public void onClick(View p1)
                {
                    final List<String> PathList=new ArrayList<String>();
					final List<ApplicationInfo> applist=new ArrayList<ApplicationInfo>();
                    final List<String> AppNameList=new ArrayList<String>();
                    PackageManager pm = getPackageManager();
                    List<ApplicationInfo> apps = pm.getInstalledApplications(PackageManager.GET_META_DATA);
                    for (ApplicationInfo app : apps)
                    {
                        if (app.metaData == null)
                            continue;
                        String nativeLibName = app.metaData.getString("net.ycxinxing.mcpebox.api.nativelibname");
                        if (nativeLibName != null && pm.checkPermission("net.ycxinxing.mcpebox.NativeC", app.packageName) == PackageManager.PERMISSION_GRANTED)
                        {
                            PathList.add(app.nativeLibraryDir + "/lib" + nativeLibName + ".so");
                            AppNameList.add(app.packageName);
							applist.add(app);
                        }
                    }

                    mDialog mdlg=new mDialog(prepareLaunch.this){

                        @Override
                        public void onButtonClick(int i)
                        {
                            et.setText(PathList.get(i));
							et.setTag(applist.get(i));

                            // TODO: Implement this method
                        }
                    };
                    mdlg.setTitle("选择已安装的Native控制终端");

                    mdlg.setList(AppNameList);
                    mdlg.show();

                    // TODO: Implement this method
                }
            });
        // TODO: Implement this method
    }
	@Override
	protected Dialog onCreateDialog(int id, Bundle args)
	{
		if (id == 1234)

		{
			Map<String, Integer> images = new HashMap<String, Integer>();
			// 下面几句设置各文件类型的图标， 需要你先把图标添加到资源文件夹
			images.put(OpenFileDlg.sRoot, R.drawable.fi_dir);	// 根目录图标
			images.put(OpenFileDlg.sParent, R.drawable.fi_dir);	//返回上一层的图标
			images.put(OpenFileDlg.sFolder, R.drawable.fi_dir);	//文件夹图标
			images.put("apk", R.drawable.fi_file);	//文件图标
			images.put(OpenFileDlg.sEmpty, R.drawable.fi_file);
			Dialog dialog = OpenFileDlg.createDialog(1234, this, "打开文件", new CallbackBundle(){
					@Override
					public void callback(Bundle bundle)
					{
						((Button)findViewById(R.id.PacketPathSButton)).setText(bundle.getString("path"));
						// TODO: Implement this method
					}
				}, ".mcpeboxpack", images);
			return dialog;
		}
		return super.onCreateDialog(id,args);
	}
}
